import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_ability/custom_ui.dart';

import 'yj_back_button.dart';

/// AppBar
class YJAppBar extends AppBar implements PreferredSizeWidget {
  YJAppBar({
    Key? key,
    this.isScaffold = false,
    this.elevation = 0,
    this.centerTitle,
    this.leading,
    this.leadingType,
    this.title,
    this.actions,
    this.shape,
    this.backgroundColor,
    this.titleSpacing = NavigationToolbar.kMiddleSpacing,
    this.isSearchBar = false,
    this.searchHintText = '搜索...',
    this.searchHintStyle = const TextStyle(
      color: Color(0xFFC9CDD4),
      fontSize: 14,
    ),
    this.searchTextStyle = const TextStyle(
      color: Colors.black87,
    ),
    this.searchBarColorTheme = const Color(0xFFC9CDD4),
    this.searchController,
    this.onTap,
    this.onChanged,
    this.onSubmitted,
  }) : super(key: key);

  final bool? isScaffold;

  final double? elevation;

  final bool? centerTitle;

  /// 返回按钮
  final Widget? leading;

  /// 按钮类型
  YJAppBarType? leadingType;

  /// 文本
  final Widget? title;

  /// 右边组件
  final List<Widget>? actions;

  /// 整个控件的边框阴影等
  final ShapeBorder? shape;

  /// 背景颜色
  final Color? backgroundColor;

  /// 文本间隔
  final double titleSpacing;

  /// 是否搜索
  final bool isSearchBar;

  /// 搜索提示文本
  final String searchHintText;

  /// 搜索提示文本样式
  final TextStyle searchHintStyle;

  /// 搜索文本样式
  final TextStyle searchTextStyle;

  ///搜索背景颜色
  final Color searchBarColorTheme;

  /// 点击回调
  final ValueChanged<String>? onChanged;

  /// 搜索提交确定
  final ValueChanged<String>? onSubmitted;

  /// 搜索监听
  final TextEditingController? searchController;

  /// 点击回调
  final GestureTapCallback? onTap;

  @override
  _YJAppBarState createState() => _YJAppBarState();

  @override
  Size get preferredSize => Size.fromHeight(44);
}

class _YJAppBarState extends State<YJAppBar> {
  final TextEditingController _searchController = TextEditingController();

  @override
  Widget build(BuildContext context) {
    assert(debugCheckHasMediaQuery(context));
    assert(debugCheckHasMaterialLocalizations(context));
    final ThemeData theme = Theme.of(context);
    final AppBarTheme appBarTheme = AppBarTheme.of(context);
    TextStyle? centerStyle =
        appBarTheme.titleTextStyle ?? theme.primaryTextTheme.headlineSmall;

    /// 左边返回箭头
    Widget? leading = SizedBox();
    if (widget.leadingType == null || widget.leadingType == YJAppBarType.back) {
      leading = ConstrainedBox(
          constraints: BoxConstraints.tightFor(width: YJSize.dp(44)),
          child: const YJBackButton(
            color: YJColors.BLACK85,
          ));
    } else if (widget.leadingType == YJAppBarType.close) {
      leading = ConstrainedBox(
          constraints: BoxConstraints.tightFor(width: YJSize.dp(44)),
          child: const YJCloseButton());
    }
    if (widget.leading != null) {
      leading = widget.leading;
    }

    /// 字体文本
    Widget? title = widget.title;
    if (title != null && centerStyle != null) {
      title = DefaultTextStyle(
        style: centerStyle,
        softWrap: false,
        overflow: TextOverflow.ellipsis,
        child: GFAppBarTitleBar(child: title),
      );
    }

    /// 右边按钮
    Widget? actions;
    if (widget.actions != null && widget.actions!.isNotEmpty) {
      actions = Row(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: widget.actions!,
      );
    }

    /// 搜索按钮
    Widget? searchBar = SizedBox();
    if (widget.isSearchBar) {
      searchBar = SizedBox(
        width: YJSize.screenWidth,
        child: Row(
          children: [
            Container(
              width: YJSize.dp(220),
              height: YJSize.dp(32),
              decoration: BoxDecoration(
                  color: Color(0xFFF3F3F3),
                  borderRadius: BorderRadius.all(Radius.circular(50))),
              child: buildTextField(),
            )
          ],
        ),
      );
    }
    Widget? toolbar = SizedBox();
    if (widget.isScaffold == true) {
      return toolbar = AppBar(
        leading: leading,
        title: title,
        backgroundColor: widget.backgroundColor,
        actions: widget.actions,
        elevation: widget.elevation,
        centerTitle: widget.centerTitle,
      );
    } else {
      toolbar = NavigationToolbar(
        leading: leading,
        middle: widget.isSearchBar ? searchBar : title,
        trailing: actions,
        centerMiddle: true,
        middleSpacing: widget.titleSpacing,
      );
      return Material(
        color: widget.backgroundColor,
        shape: widget.shape,
        child: Semantics(
          explicitChildNodes: true,
          child: Container(
            height: YJSize.dp(44),
            child: toolbar,
          ),
        ),
      );
    }
  }

  TextField buildTextField() {
    final controller = widget.searchController ?? _searchController;
    return TextField(
      cursorColor: widget.searchBarColorTheme,
      style: widget.searchTextStyle,
      textAlign: TextAlign.start,
      decoration: InputDecoration(
        prefixIcon: YJIconButton(
          icon: Icon(
            Icons.search,
            color: widget.searchBarColorTheme,
            size: 18,
          ),
          type: YJButtonType.transparent,
          onPressed: () {
            print("点击搜索 -- ${controller.text}");
          },
        ),
        suffixIcon: YJIconButton(
          icon: Icon(
            Icons.close,
            color: widget.searchBarColorTheme,
            size: 20,
          ),
          type: YJButtonType.transparent,
          onPressed: () {
            widget.onSubmitted?.call('');
            setState(() {
              controller.text = '';
            });
          },
        ),
        //contentPadding和border的设置是为了让TextField内容实现上下居中
        contentPadding: EdgeInsets.all(0),
        hintText: widget.searchHintText,
        hintStyle: widget.searchHintStyle,
        border: InputBorder.none,
        focusedBorder: UnderlineInputBorder(
          borderSide:
              BorderSide(color: Colors.transparent, width: YJSize.dp(0.5)),
        ),
        enabledBorder: UnderlineInputBorder(
          borderSide: BorderSide(color: Colors.transparent),
        ),
      ),
      onTap: widget.onTap,
      onChanged: widget.onChanged,
      controller: widget.searchController ?? _searchController,
      onSubmitted: widget.onSubmitted,
    );
  }
}

const double _kLeadingWidth = kToolbarHeight;

class GFAppBarTitleBar extends SingleChildRenderObjectWidget {
  const GFAppBarTitleBar({Key? key, required Widget child})
      : super(key: key, child: child);

  @override
  RenderGFAppBarTitleBar createRenderObject(BuildContext context) =>
      RenderGFAppBarTitleBar(
        textDirection: Directionality.of(context),
      );

  @override
  void updateRenderObject(
      BuildContext context, RenderGFAppBarTitleBar renderObject) {
    renderObject.textDirection = Directionality.of(context);
  }
}

class RenderGFAppBarTitleBar extends RenderAligningShiftedBox {
  RenderGFAppBarTitleBar({
    RenderBox? child,
    TextDirection? textDirection,
  }) : super(
          child: child,
          alignment: Alignment.center,
          textDirection: textDirection,
        );

  @override
  void performLayout() {
    final BoxConstraints innerConstraints =
        constraints.copyWith(maxHeight: double.infinity);
    child?.layout(
      innerConstraints,
      parentUsesSize: true,
    );
    if (child != null) {
      size = constraints.constrain(child!.size);
    }
    alignChild();
  }
}
